#include "key_device.h"

KeyDevice::KeyDevice(QObject *parent) : QObject{parent} {}

KeyDevice::~KeyDevice()
{
    if (serialPort != nullptr && serialPort->isOpen())
    {
        serialPort->clear();
        serialPort->close();
        serialPort->deleteLater();
    }
}

bool KeyDevice::InitDevice(const QString &device, int baudRate)
{
    // Open serial port
    serialPort = new QSerialPort(this);
    serialPort->setPortName(device);
    serialPort->setBaudRate(baudRate);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);

    serialPort->open(QIODevice::ReadOnly);
    if (!serialPort->isOpen())
    {
        qDebug("open serial port failed");
        return false;
    }

    // timer = new QTimer(this);
    // timer->setInterval(10);
    // connect(timer, &QTimer::timeout, this, &KeyDevice::ReadData);
    // timer->start();

    connect(serialPort, &QSerialPort::readyRead, this, &KeyDevice::ReadData);
    return true;
}

bool KeyDevice::CheckFrame(const QByteArray &frame)
{
    unsigned char code = 0;
    for (int i = 0; i < frame.size() - 1; i++)
    {
        code += frame[i];
    }
    code = ~code;
    return code == frame[frame.size() - 1];
}

void KeyDevice::DecodeFrame(const QByteArray &frame)
{
    int count = frame[3];
    for (int i = 0; i < count; i++)
    {
        unsigned char code = frame[i + 4];
        KeyCode key = static_cast<KeyCode>(code);
        emit OnInput(key);
    }
}

void KeyDevice::ReadData()
{
    QByteArray receive = serialPort->readAll();
    for (auto byte : receive)
    {
        buffer.append(byte);
        if (buffer.size() > 1 && static_cast<unsigned char>(buffer[1]) == buffer.size() - 2)
        {
            if (CheckFrame(buffer))
            {
                DecodeFrame(buffer);
            }
            else
            {
                qDebug("key device frame error");
            }
            buffer.clear();
        }
    }
}